import requests
import time
from config.config import current_config

# HTTP客户端模块是框架的核心组件
class HttpClient:
    def __init__(self):
        # 创建session对象，保持会话状态
        self.session = requests.Session()
        # 存储重要的cookie信息
        self.auth_cookies = {}
        # 登录状态标记
        self.is_logged_in = False

    def request(self, method, url, **kwargs):
        """基础请求方法，包含重试逻辑"""
        # 如果是相对URL，则拼接基础URL
        if not url.startswith('http'):
            url = f"{current_config.BASE_URL}{url}"

        # 添加默认超时
        kwargs.setdefault('timeout', current_config.TIMEOUT)

        if 'headers' not in kwargs:
            kwargs['headers'] = {}

        # 重试逻辑
        for i in range(current_config.RETRY_COUNT):
            try:
                response = self.session.request(method, url, **kwargs)
                # 自动处理JSON响应
                try:
                    response_data = response.json()
                except ValueError:
                    response_data = response.text

                # 添加响应信息到结果中
                result = {
                    'status_code': response.status_code,
                    'headers': dict(response.headers),
                    'data1': response_data,
                    'url': response.url
                }

                return result
            except requests.RequestException as e:
                if i == current_config.RETRY_COUNT - 1:
                    raise
                time.sleep(1)  # 重试间隔

    def get(self, url, params=None, **kwargs):
        """发送GET请求"""
        return self.request('GET', url, params=params, **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        """发送POST请求"""
        return self.request('POST', url, data=data, json=json, **kwargs)

    def put(self, url, data=None, **kwargs):
        """发送PUT请求"""
        return self.request('PUT', url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        """发送DELETE请求"""
        return self.request('DELETE', url, **kwargs)
    
    def extract_login_cookies(self, response=None):
        """
        从登录响应或当前session中提取登录相关的cookie
        如果提供了response参数，则从响应中提取
        否则从当前session中获取所有cookie
        """
        # 从响应中提取cookie
        if response and hasattr(response, 'cookies'):
            for cookie in response.cookies:
                if cookie.name.lower() in ['jsessionid', 'token', 'sessionid', 'auth']:
                    self.auth_cookies[cookie.name] = cookie.value
        # 或者从session中获取所有cookie
        else:
            for cookie_name, cookie_value in self.session.cookies.get_dict().items():
                if cookie_name.lower() in ['jsessionid', 'token', 'sessionid', 'auth']:
                    self.auth_cookies[cookie_name] = cookie_value
        
        # 如果成功提取到认证cookie，标记为已登录
        if self.auth_cookies:
            self.is_logged_in = True
        
        return self.auth_cookies
    
    def get_cookie_value(self, cookie_name):
        """获取指定名称的cookie值"""
        return self.auth_cookies.get(cookie_name)
    
    def clear_login_cookies(self):
        """清除登录相关的cookie信息"""
        self.auth_cookies.clear()
        self.is_logged_in = False
        self.session.cookies.clear()
    
    def get_login_status(self):
        """获取当前登录状态"""
        return self.is_logged_in


# 创建全局实例，方便使用
http = HttpClient()
